/**    
* @Title: UserDataListener.java
* @Package: org.vdalf.gsgz.service
* @author vDalf 2020-09-26 16:28:02 下午4:28:02
* @Copyright © 2020 vDalf Block-Chain Foundation (In Preparation Non-Governmental Organization) All rights reserved.
*/
package org.vdalf.gsgz.listener;

import java.math.BigDecimal;
import java.time.LocalDateTime;
import java.util.HashMap;
import java.util.Map;
import java.util.Optional;
import java.util.TreeMap;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.ApplicationArguments;
import org.springframework.boot.ApplicationRunner;
import org.springframework.core.Ordered;
import org.springframework.stereotype.Component;
import org.vdalf.gsgz.config.RobotConfig;
import org.vdalf.gsgz.entities.PlanEntrust;
import org.vdalf.gsgz.entities.UserData;
import org.vdalf.gsgz.enums.EnumConditions;

/**    
* @Title: UserDataListener.java
* @Package: org.vdalf.gsgz.service
* @Description: 
* @author vDalf 2020-09-26 16:28:02 下午4:28:02
*/
@Component
public class UserDataListener implements ApplicationRunner,Ordered{

	private static final Logger logger = LoggerFactory.getLogger(UserDataListener.class);
	
	@Autowired
	private RobotConfig robotConfig;
	
	@Override
	public void run(ApplicationArguments args) throws Exception {
		logger.info("user data load start.......{}",robotConfig.getOkexRobotProperties().getStrategys());
		robotConfig.getOkexRobotProperties().getStrategys().stream().forEach(c->{
			Map<EnumConditions, TreeMap<BigDecimal, PlanEntrust>> entrusts4Market = Optional.ofNullable(UserData.getInstance().getPlanEntrusts().get(c.getMarket())).orElseGet(()->{
				Map<EnumConditions, TreeMap<BigDecimal, PlanEntrust>> entrusts = new HashMap<>();
				UserData.getInstance().getPlanEntrusts().put(c.getMarket(), entrusts);
				return entrusts;
			});
			EnumConditions condition = c.getCondition();
			TreeMap<BigDecimal, PlanEntrust> queue = Optional.ofNullable(entrusts4Market.get(condition)).orElseGet(()->{
				TreeMap<BigDecimal, PlanEntrust> map = new TreeMap<BigDecimal, PlanEntrust>((a,b)-> EnumConditions.大于==condition?a.compareTo(b):b.compareTo(a));
				entrusts4Market.put(condition, map);
				return map;
			});
			queue.put(c.getTarget(), new PlanEntrust(UserData.nextId(), c.getMarket(), condition.getCode(), c.getTarget(), c.getAction().getCode(), c.getOrderPrice(), c.getOrderVolume(), LocalDateTime.now(), "1"));
		});
		logger.info("user data load end.......{}",UserData.getInstance());
	}

	@Override
	public int getOrder() {
		return 3;
	}

}
